// import axios from 'axios';

const cartModule = {
    namespaced:true,
    state: {
        cartList:JSON.parse(localStorage.getItem("cart")) || [],
        allSelected:JSON.parse(localStorage.getItem("allSelected")) || false,
    },
    mutations: {
        // 点击加入购物车
        CLICK_ADD_CART(state,item){
            // 找到重复的商品
            var flag = false;
            state.cartList.forEach(element => {
                if(element._id === item._id){
                    flag = true;
                    element.count++;
                }
            });
            if(!flag){
                item.count = 1;
                item.checked = false;
                state.cartList.push(item);
            }
            console.log(state.cartList)
            localStorage.setItem("cart",JSON.stringify(state.cartList));
        },
        // 单选框
        CHANGE_STORE_CHECKED(state,item){
            var tempItem = state.cartList.find(element => {
                return element._id === item.id;
            })
            if(tempItem){
                tempItem.checked = item.checked;
            }
            state.allSelected = state.cartList.every(element => {
                return element.checked === true;
            });
            // 存储数据
            localStorage.setItem("allSelected",JSON.stringify(state.allSelected));
            localStorage.setItem("cart",JSON.stringify(state.cartList));
        },
        // 全选框
        CHANGE_ALL_SELECTED(state,boolean){
            state.allSelected = boolean;
            state.cartList.forEach(element => {
                element.checked = boolean;
            })
            localStorage.setItem("allSelected",JSON.stringify(state.allSelected));
            localStorage.setItem("cart",JSON.stringify(state.cartList));
        },
        // 绑定值改变
        CHANGE_COUNT(state,item){
            state.cartList.forEach(element => {
                if(element._id == item.id){
                    element.count = item.currentValue;
                }
            })
            localStorage.setItem("cart",JSON.stringify(state.cartList));
        },
        // 点击 删除
        CLICK_DELETE(state, id) { 
            state.cartList.forEach((element, index) => {   // 遍历购物车数据
                if (element._id == id) {       //判断传过来的id是否在cartList数据中，如果找到就删除
                    state.cartList.splice(index, 1);
                }
            })
            localStorage.setItem("cart", JSON.stringify(state.cartList)); //保存到本地
        },
    },
    getters:{
        // 选中商品 总价
        totalPrice(state) {
            var tempPrice = 0;
            state.cartList.forEach(element => {
                if(element.checked){
                    tempPrice += element.count*element.salePrice;
                }
            })
            return tempPrice;
        },
    },
    actions: {
        
    },
    modules: {
    }
}

export default cartModule;